//
//  ListViewController.m
//  JXPagerViewExample-OC
//
//  Created by jiaxin on 2019/12/30.
//  Copyright © 2019 jiaxin. All rights reserved.
//

#import "ListViewController.h"
#import "UIWindow+JXSafeArea.h"
#import "MailCell.h"
#import "AbulkCell.h"
#import "MailDetailsVC.h"

@interface ListViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
@property (assign, nonatomic)int page;
@property (assign, nonatomic)int defaultStartPage;
@end

@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailCell" bundle:nil] forCellReuseIdentifier:@"MailCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"AbulkCell" bundle:nil] forCellReuseIdentifier:@"AbulkCell"];
    //列表的contentInsetAdjustmentBehavior失效，需要自己设置底部inset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, UIApplication.sharedApplication.keyWindow.jx_layoutInsets.bottom, 0);
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = VCBgcolor;
    self.defaultStartPage = 1;
    self.page = 1;
    [self setRefresh];
    SVPShowInternetWaiting;
    [self requestData];

    
}

// 设置刷新
- (void)setRefreshNoEmpty
{
    self.page = self.defaultStartPage;
    
    // 下拉刷新
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = weakSelf.defaultStartPage;
        [weakSelf requestData];
    }];

    // 上拉加载
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    [footer setTitle:@"" forState:MJRefreshStateNoMoreData];
//    footer.automaticallyHidden = YES;

    self.tableView.mj_header = header;
    self.tableView.mj_footer = footer;
}

- (void)setRefresh
{
    [self setRefreshNoEmpty];
    // 无数据页面
//    [self setEmptyView];
}

- (void)endRefresh
{
    if (self.tableView) {
        [self.tableView.mj_footer resetNoMoreData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }

}

- (void)endRefreshNoMoreData
{
    if (self.tableView) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }

}

- (void)requestData
{
    if (self.type == 0) {
        SVPShowInternetWaiting
        // 请求列表
         WeakSelf(ws)
         [NetRequestTool postUrl:@"sku/queryGoodsList" parameters:@{@"page":@(self.page), @"limit":@"10",@"business_id":self.business_id} success:^(id responseObject) {
             NSMutableArray *arr = [MailGoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
             if (self.page==self.defaultStartPage) {
                 ws.dataSource = arr;
             }
             else {
                 [ws.dataSource addObjectsFromArray:arr];
             }
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self.tableView reloadData];
             });
             
             // 控制页数
             NSDictionary *page = [responseObject objectForKey:@"page"];
             if ([page isKindOfClass:NSDictionary.class]) {
                 NSInteger totalP = [page[@"total_page"] integerValue];
                 if (totalP > self.page) {
                     self.page++;
                     [self endRefresh];
                 }
                 else {
                     [self endRefreshNoMoreData];
                 }
             }
             else {
                 [self endRefreshNoMoreData];
             }
         } failure:^(NSInteger statusCode) {
             [ws endRefresh];
         } finish:^{

         }];
    }else if (self.type == 1) {
        SVPShowInternetWaiting
        // 请求列表
         WeakSelf(ws)
         [NetRequestTool postUrl:@"sku/queryYkGoodsList" parameters:@{@"page":@(self.page), @"limit":@"10",@"business_id":self.business_id} success:^(id responseObject) {
             NSMutableArray *arr = [MailGoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
             if (self.page==self.defaultStartPage) {
                 ws.dataSource = arr;
             }
             else {
                 [ws.dataSource addObjectsFromArray:arr];
             }
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self.tableView reloadData];
             });
             
             // 控制页数
             NSDictionary *page = [responseObject objectForKey:@"page"];
             if ([page isKindOfClass:NSDictionary.class]) {
                 NSInteger totalP = [page[@"total_page"] integerValue];
                 if (totalP > self.page) {
                     self.page++;
                     [self endRefresh];
                 }
                 else {
                     [self endRefreshNoMoreData];
                 }
             }
             else {
                 [self endRefreshNoMoreData];
             }
         } failure:^(NSInteger statusCode) {
             [ws endRefresh];
         } finish:^{

         }];
    }else {
        SVPShowInternetWaiting
        // 请求列表
         WeakSelf(ws)
         [NetRequestTool postUrl:@"sku/queryTgGoodsList" parameters:@{@"page":@(self.page), @"limit":@"10",@"business_id":self.business_id} success:^(id responseObject) {
             NSMutableArray *arr = [MailGoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
             if (self.page==self.defaultStartPage) {
                 ws.dataSource = arr;
             }
             else {
                 [ws.dataSource addObjectsFromArray:arr];
             }
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self.tableView reloadData];
             });
             
             // 控制页数
             NSDictionary *page = [responseObject objectForKey:@"page"];
             if ([page isKindOfClass:NSDictionary.class]) {
                 NSInteger totalP = [page[@"total_page"] integerValue];
                 if (totalP > self.page) {
                     self.page++;
                     [self endRefresh];
                 }
                 else {
                     [self endRefreshNoMoreData];
                 }
             }
             else {
                 [self endRefreshNoMoreData];
             }
         } failure:^(NSInteger statusCode) {
             [self endRefresh];
         } finish:^{

         }];
    }
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    self.tableView.frame = self.view.bounds;
}


#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.type == 0 || self.type == 1) {
        MailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataSource[indexPath.row];
        self.tableView.rowHeight = 135;

        return cell;
    }else {
        AbulkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AbulkCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataSource[indexPath.row];
        self.tableView.rowHeight = 150;

        return cell;
    }
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MailDetailsVC *vc = [[MailDetailsVC alloc] init];
    vc.goodsModel = self.dataSource[indexPath.row];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
}

#pragma mark - JXPagingViewListViewDelegate

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}

- (void)listWillAppear {
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidAppear {
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listWillDisappear {
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidDisappear {
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

@end
